package com.leyou.page.service;

import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    public Map<String, Object> loadItemData(Long spuId) {
        // TODO 尝试获取redis，如果有，直接返回

        // 查询spu
        SpuDTO spu = itemClient.querySpuById(spuId);
        // 查询specs
        List<SpecGroupDTO> specs = itemClient.querySpecs(spu.getCid3());

        Map<String, Object> map = new HashMap<>();
        map.put("categories", spu.getCategories());
        map.put("brand", spu.getBrand());
        map.put("spuName", spu.getName());
        map.put("subTitle", spu.getSubTitle());
        map.put("detail", spu.getSpuDetail());
        map.put("skus", spu.getSkus());
        map.put("specs", specs);

        // TODO 数据加入redis
        return map;
    }

    @Autowired
    private SpringTemplateEngine templateEngine;

    private static final String HTML_DIR = "C:\\lesson\\heima78\\nginx-1.12.2\\html\\item";

    public void createItemHtml(Long spuId) {
        // 1.准备上下文
        Context context = new Context();
        context.setVariables(loadItemData(spuId));

        // 2.准备文件地址
        File file = new File(HTML_DIR, spuId + ".html");

        // 3.准备输出流，关联硬盘中的某个文件
        try (PrintWriter writer = new PrintWriter(file, "UTF-8")) {
            // 4.渲染页面，并写出
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            log.error("文件写入失败，原因：{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 线程池的创建方案
     */
    private static final Executor es = new ThreadPoolExecutor(
            20,
            50,
            60L,
            TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(),
            r -> new Thread(r, "create-html-thread")
    );

    public void asyncCreateHtml(Long spuId) {
        es.execute(() -> createItemHtml(spuId));
    }

    public void deleteHtml(Long spuId) {
        File file = new File(HTML_DIR, spuId + ".html");
        if(file.exists()){
            boolean isDelete = file.delete();
            if(!isDelete){
                throw new RuntimeException("商品删除失败！");
            }
        }
    }
}
